package com.lgst.carousel;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.Gravity;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;

/**
 * Created by L on 2017/2/15.
 */

public class CarouselIndicator extends RadioGroup {
    private int mPointDrawable;

    public CarouselIndicator(Context context) {
        super(context);
        mPointDrawable = R.drawable.shape_point;
    }

    public CarouselIndicator(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.CarouselIndicator);
        mPointDrawable = ta.getInt(R.styleable.CarouselIndicator_point, R.drawable.shape_point);
        ta.recycle();
    }

    public void init(int pointCount) {
        setOrientation(HORIZONTAL);
        setGravity(Gravity.CENTER_HORIZONTAL);
        initPoint(pointCount);
    }

    private void initPoint(int pointCount) {
        for (int i = 0; i < pointCount; i++) {
            RadioButton radiobtn = new RadioButton(getContext());
            radiobtn.setButtonDrawable(mPointDrawable);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(dip2px(16), dip2px(16));
            radiobtn.setLayoutParams(params);
            addView(radiobtn);
        }
    }

    public void checkPoint(int index){
        RadioButton radioButton = (RadioButton) getChildAt(index);
        radioButton.setChecked(true);
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public int dip2px(float dpValue) {
        final float scale = getContext().getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
}
